package com.jluzh10.learning.service.Impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jluzh10.learning.dao.ChapterMapper;
import com.jluzh10.learning.dao.QuestionMapper;
import com.jluzh10.learning.domain.Chapter;
import com.jluzh10.learning.domain.ChapterExample;
import com.jluzh10.learning.domain.Question;
import com.jluzh10.learning.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author cj
 * @date 5/25/2019
 */
@Service
@Transactional
public class QuestionServiceImpl implements QuestionService {

    private final QuestionMapper quMapper;



    @Autowired
    private ChapterMapper cm;

    @Autowired
    public QuestionServiceImpl(QuestionMapper quMapper) {
        this.quMapper = quMapper;
    }



    /**
     * 新增一个问题
     */
      public int addQu(Question nodeQu) {
            return quMapper.insertSelective(nodeQu);
      }

    /**
     * 为下拉框查询课程对应的章节
     * @param courseId
     * @return Chapter
     */
    @Override
    public List<Chapter> searchTitleService(Integer courseId) {
        ChapterExample ce = new ChapterExample();
        //等价于SELECT * FROM t_chapter WHERE course_id=1 and state =1;
        ce.createCriteria().andCourseIdEqualTo(courseId).andStateEqualTo((byte)1);
        ce.setOrderByClause("sort");
        List<Chapter> chapters = cm.selectByExample(ce);
        return chapters;
    }

    /**
     * 查询某个问题和对应用户
     *
     * @return
     */
    @Override
    public Question searchQNUserService(Integer id) {
         //根据问题id查询出当前问题
        Question q = quMapper.selectByPrimaryKey(id);
        /*更新问题的浏览次数*/

        int browseNum = q.getBrowseNum();

        browseNum++;
        q.setBrowseNum(browseNum);
        quMapper.updateByPrimaryKey(q);
        return quMapper.searchQNUser(id);
    }

    /**
     * 根据课程id查询所有问题和对应的最新回答
     * @return question
     */
    public List<Question> searchAllQuestionService(Question question){
        //当章节id或发表用户id为0时，删除条件
        if (question.getChapterId()==0){
            question.setChapterId(null);
        }
        if (question.getUserId()==0){
            question.setUserId(null);
        }
        return quMapper.searchAllQuestion(question);
    }


}
